package com.derbysoft.lowcostadapter.web.action.admin.hotel;

import com.derbysoft.common.web.struts2.support.PaginateActionSupport;
import com.derbysoft.lowcostadapter.commons.model.Hotel;
import com.derbysoft.lowcostadapter.commons.model.Status;
import com.derbysoft.lowcostadapter.commons.repository.HotelRepository;
import com.derbysoft.lowcostadapter.commons.utils.CheckUtils;
import com.opensymphony.xwork2.ActionContext;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AddAction extends PaginateActionSupport {
    private static final String ADD = "add";
    private static final String EDIT = "edit";

    @Autowired
    private HotelRepository hotelRepository;

    private Hotel hotel;

    public static final String IMPORT_VIEW = "import";

    private static final int MAX_LINES = 500;

    private String hotels;

    private String result;

    @Action("update")
    public String update() {
        if (hotel.getPropertyID() != 0
                && !StringUtils.isBlank(hotel.getPassport())
                && hotel.getStatus() != null) {
            Hotel oldHotel = hotelRepository.load(hotel.getPropertyID());
            if (oldHotel != null) {
                oldHotel.setPassport(hotel.getPassport());
                oldHotel.setName(hotel.getName());
                oldHotel.setStatus(hotel.getStatus());
                hotelRepository.save(oldHotel);
            }
        }
        ((HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST))
                .setAttribute("success", hotel.getPropertyID() + " success !!");
        return EDIT;
    }

    @Action("addHotel")
    public String add() {
        if (hotel.getPropertyID() != 0
                && !StringUtils.isBlank(hotel.getPassport())
                && hotel.getStatus() != null) {
            if (hotelRepository.load(hotel.getPropertyID()) != null) {
                ((HttpServletRequest) ActionContext.getContext()
                        .get(ServletActionContext.HTTP_REQUEST))
                        .setAttribute("propertyID_error", hotel.getPropertyID() + " : had already exists !!");
                return view();
            }
            if (hotelRepository.findByPassport(hotel.getPassport()) != null) {
                ((HttpServletRequest) ActionContext.getContext()
                        .get(ServletActionContext.HTTP_REQUEST))
                        .setAttribute("passport_error", hotel.getPassport() + " : had already exists !!");
                return view();
            }
            hotelRepository.save(hotel);
        }
        ((HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST))
                .setAttribute("success", hotel.getPropertyID() + " success !!");
        return ADD;
    }

    @Action("view")
    public String view() {
        return ADD;
    }

    @Action("edit")
    public String edit() {
        if (hotel != null && hotel.getPropertyID() != 0) {
            hotel = hotelRepository.load(hotel.getPropertyID());
        }
        return EDIT;
    }

    @Action("importView")
    public String importView() {
        return IMPORT_VIEW;
    }

    @Action("batchImport")
    public String batchImport() {
        if (StringUtils.isBlank(hotels)) {
            result = "invalid lines";
            return IMPORT_VIEW;
        }

        Map<String, Hotel> mappingMap = new HashMap<String, Hotel>();
        String[] lines = hotels.replace("\r\n", "\n").split("\n");
        for (int i = 0; i < lines.length && i < MAX_LINES; i++) {
            String[] columns = lines[i].split("\\|");
            if (columns == null || columns.length != 4) {
                continue;
            }
            if (CheckUtils.checkNumber(columns[0]) && hotelRepository.load(Integer.parseInt(columns[0])) != null) {
                continue;
            }
            Hotel hotelMap = new Hotel();
            hotelMap.setPropertyID(Integer.parseInt(columns[0].trim()));
            hotelMap.setPassport(columns[1].trim());
            hotelMap.setName(columns[2].trim());
            hotelMap.setStatus(columns[3].trim().toUpperCase().equals("ENABLED") ? Status.ENABLED : Status.DISABLED);
            mappingMap.put(columns[0].trim() + "_" + columns[1].trim(), hotelMap);
        }
        List<Hotel> newHotels = new ArrayList<Hotel>(mappingMap.values());
        StringBuilder builder = new StringBuilder();
        for (Hotel mapping : newHotels) {
            builder.append("[").append(mapping.getPropertyID()).append("]").append(" OK.").append("<br>");
        }
        result = builder.toString();
        hotelRepository.saveAll(newHotels);
        return IMPORT_VIEW;
    }

    public String getHotels() {
        return hotels;
    }

    public void setHotels(String hotels) {
        this.hotels = hotels;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public Hotel getHotel() {
        return hotel;
    }

    public void setHotel(Hotel hotel) {
        this.hotel = hotel;
    }
}
